package org.jeecg.modules.cascv.image.service.merge.liangxianggui;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.RandomUtil;
import com.NativeImageIO;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.ImageService;
import org.jeecg.modules.cascv.image.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author
 * @Version 2022/3/21
 * description;
 */
@Service
@Slf4j
public class LiangxiangguiApp3or4Service extends ImageService {

    @Value("${imageurl}")
    private String imageurl;

    @Autowired
    private TaskExecutePool taskExecutePool;

    @Override
    public String idsNames() {
        return "TGMTYY1401_09CH_31_TPSRAPP3,TGMTYY1401_09CH_31_TPSRAPP4,6D1FH_40H,6D20H_40H";
    }

    @Override
    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {

        JSONObject conJson = jsonObject.getJSONObject("Content");
//打印报错不连续的包序号
        String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if(null==lastPackageNum){
            LaptopConstant.packageNumMap.put(key,intpackageNum);
        }else {
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:"+intpackageNum+"，上一包包序号:"+lastPackageNum);
                }
            }
        }
        String secondStr = jsonObject.getString("second");
        long second = Long.parseLong(secondStr);
        String subSecondStr = jsonObject.getString("subsecond");
        secondStr = LaptopUtil.toDayHoursMinSec(second);

        String nextImageNum = conJson.getString(LaptopConstant.IMAGENUM_FIELD_MAP.get(idsName));
        String dataFrames = conJson.getString(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
        nextImageNum = nextImageNum.split(";")[0];//获取图像编号
       // dataFrames = dataFrames.split(";")[1];
       // dataFrames = dataFrames.substring(2).trim(); //获取需要解析的图像数据
        // 那边给的数据需要这样 没有0x 去掉结尾的H
        //dataFrames = dataFrames.substring(7, dataFrames.length() - 10);
        dataFrames = dataFrames.split(";")[1].substring(2).trim();
        StringBuilder queue = LaptopConstant.imageData.get(key);
        composite(idsName, key, conJson, dataFrames, queue, nextImageNum, secondStr, subSecondStr);

        return null;
    }


    public boolean composite(String idsName, String key, JSONObject content, String dataFrames, StringBuilder queue, String currImageNum, String secondStr, String subSecondStr) {
        //获取上一个图像编号
        String lastImageNum = LaptopConstant.imageNumMap.get(key);
        //获取宽度
        int width = Integer.parseInt((content.getString(LaptopConstant.WIDTH_FIELD_MAP.get(idsName))).split(";")[0]);
        //获取高度
        int height = Integer.parseInt((content.getString(LaptopConstant.HEIGHT_FIELD_MAP.get(idsName))).split(";")[0]);

       // System.out.println("imageNum=" + lastImageNum);
        //System.out.println("nextImageNum=" + currImageNum);

        //判断图像编号是否相同，不相同生成图片 相同继续拼接数据
        if (lastImageNum == null || lastImageNum.equals(currImageNum)) {
            if (queue != null) {
                queue.append(dataFrames);
            } else {
                queue = new StringBuilder();
                queue.append(dataFrames);
            }
            LaptopConstant.imageData.put(key, queue);
        } else {


   //         String imgHexStr = LaptopConstant.imageData.get(key).toString();
            StringBuilder stringBuilder = LaptopConstant.imageData.get(key);

            while (stringBuilder.length() < 2592 * 1944 * 2) {
                stringBuilder.append("0");
            }
            while (stringBuilder.length() > 2592 * 1944 * 2) {
                stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length());
            }
            //将数据 转16进制的byte型数组
            String imgHexStr = stringBuilder.toString();




            if (imgHexStr.length()/2 >= width * height) {
                CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
                    long start = System.currentTimeMillis();
                    byte[] bytes = HexUtil.decodeHex(imgHexStr);
                        //随机字符
                        String idStr = IdWorker.getIdStr();
                        int png = LaptopConstant.nativeImageIO.write(bytes, height, width, "/data/images/", idStr + ".png", "png");
                        String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr + ".png";
                        System.out.println("imageUrl = " + imageUrl);
                        content.put("imageUrl", imageUrl);
                        content.put("idsName", idsName);

                        //获取时间
                        String[] split = secondStr.split(":");
                        content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
                        content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
                        //将图片添加到map
                    content.put("key", key);
                    log.info("两相柜6D1FH_40H,6D20H_40H 合成图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");
                    return content;
                },taskExecutePool.threadPoolTaskExecutor2());
                LaptopConstant.imageFutureList.add(future);
            }
            //获取数据 并添加
            queue = new StringBuilder();
            queue.append(dataFrames);
            LaptopConstant.imageData.put(key, queue);
        }
        //存入图像编号到map
        LaptopConstant.imageNumMap.put(key, currImageNum);
        return true;
    }


    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll");
        //D:\图像数据\两相柜    D:\pc_workspace\
        List<String> strings = FileUtil.readUtf8Lines("D:\\pc_workspace\\两相系统实验柜1401\\TPSR监视CCD1.txt");

        LiangxiangguiApp3or4Service liangxiangguiApp3or4Service = new LiangxiangguiApp3or4Service();
        for (String string : strings) {
            //将str转化为相应的JSONObject对象
            JSONObject jsonObject = JSONObject.parseObject(string);
            liangxiangguiApp3or4Service.merge(jsonObject, "TGMTYY1401_09CH_31_TPSRAPP3", "TGMTYY1401_09CH_31_TPSRAPP3");
        }
    }
}
